<template>
  <a-card>
    <h1><b>新建出库单</b></h1>

    <div class="row">
      <span class="label required">出库单类型</span>
      <a-radio-group v-model:value="formData.deliveryType">1回收退货 2第三方销售 3线下销售
        <a-radio :value="1" disabled>回收退货</a-radio>
        <a-radio :value="2">第三方销售</a-radio>
        <a-radio :value="3">线下销售</a-radio>
      </a-radio-group>
    </div>
    <div class="row">
      <span class="label required">出库方式</span>
      <a-radio-group v-model:value="formData.deliveryWay">
        <a-radio :value="1">快递配送</a-radio>
        <a-radio :value="2">线下配送</a-radio>
      </a-radio-group>
    </div>
    <div class="row">
      <span class="label required">物流公司</span>
      <a-radio-group v-model:value="formData.expType">
        <a-radio :value="1">顺丰快递</a-radio>
        <a-radio :value="2">其他快递</a-radio>
      </a-radio-group>
    </div>
    <div class="row">
      <span class="label required">邮费承担</span>
      <a-radio-group v-model:value="formData.freightFlag">
        <a-radio :value="0">我司承担</a-radio>
        <a-radio :value="1">用户承担</a-radio>
      </a-radio-group>
    </div>
    <div class="row">
      <span class="label required">收件人</span>
      <a-input v-model:value="formData.lnker" placeholder="请输入收件人" style="width: 300px"/>
    </div>
    <div class="row">
      <span class="label required">收件人联系方式</span>
      <a-input v-model:value="formData.lnktel" placeholder="请输入收件人联系方式"
               style="width: 300px"/>
    </div>
    <div class="row">
      <span class="label required">收件地址</span>
      <a-cascader v-model:value="expareaCode" :options="regionData"
                  placeholder="请选择"
                  style="width: 400px"
                  @change="areaChange"/>
    </div>
    <div class="row">
      <span class="label required" style="align-self: flex-start">详细地址</span>
      <a-textarea v-model:value="formData.expdtl" :maxlength="200"
                  placeholder="请输入详细地址"
                  show-count
                  style="width: 400px"/>
    </div>


    <div style="margin-bottom: 8px">
      <a-button type="primary" @click="showAddDeviceModal">添加设备</a-button>
    </div>
    <a-table :columns="deviceTableColumns" :data-source="deviceList" :scroll="{ x: 1200 }">
      <template #bodyCell="{ column,record,text }">

        <template v-if="column.dataIndex === 'category'">
          {{ text === 1 ? '手机' : '平板' }}
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button danger type="link" @click="deleteDevice(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>


    <div class="row" style="margin: 48px 0;padding-left: 128px">
      <a-button v-once style="margin-right: 24px" @click="cancel">取消</a-button>
      <a-button v-once type="primary" @click="save">保存</a-button>
    </div>

  </a-card>


  <!--  添加和修改对话框-->
  <a-modal :visible="addDeviceModal.visible" title="选择设备" width="1200px" @cancel="hideAddDeviceModal" ok-text="使用已选设备"
           @ok="saveAddDevice">

    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item class="smart-query-form-item" label="机器信息">
          <a-input v-model:value="queryDeliveryDeviceCondition.keyword" placeholder="请输入机器编码/序列号/IMEI" style="width: 260px"/>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="型号">
          <a-input v-model:value="queryDeliveryDeviceCondition.modelName" placeholder="请输入机器型号" style="width: 200px"/>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="库存状态">
          <a-select v-model:value="queryDeliveryDeviceCondition.status"
                    allowClear placeholder="全部" style="width: 100px">
            <a-select-option :value="0">正常</a-select-option>
            <a-select-option :value="1">冻结</a-select-option>
            <a-select-option :value="2">已出库</a-select-option>
            <a-select-option :value="3">待出库</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="仓储区">
          <a-select v-model:value="queryDeliveryDeviceCondition.storageId" :field-names="{label: 'storageName',value: 'id'}"
                    :options="storageAreaOptions"
                    allowClear
                    placeholder="全部" style="width: 160px" @change="storageAreaChange">
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="货架">
          <a-select v-model:value="queryDeliveryDeviceCondition.storageRackId"
                    :field-names="{label: 'rackName',value: 'id'}"
                    :options="storageRackOptions"
                    allowClear placeholder="全部" style="width: 160px">
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="所属品牌">
          <a-select v-model:value="queryDeliveryDeviceCondition.brandId"
                    :field-names="{label: 'brandName',value: 'id'}"
                    :options="brandOptions"
                    allowClear placeholder="全部" style="width: 160px">
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="所属品类">
          <a-select v-model:value="queryDeliveryDeviceCondition.category"
                    allowClear placeholder="全部" style="width: 160px">
            <a-select-option :value="0">手机</a-select-option>
            <a-select-option :value="1">平板</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button type="primary" @click="resetPageNumAjaxQuery">
            <template #icon>
              <SearchOutlined/>
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined/>
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>

    <a-table :columns="serviceDeviceTableColumns"
             :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: rowSelectionChange,getCheckboxProps }"
             :pagination="false"
             rowKey="id"
             :data-source="serviceDeviceList" :scroll="{ x: 1200 }">
      <template #bodyCell="{ column,record,text }">
        <template v-if="column.dataIndex === 'category'">
          {{ text === 1 ? '手机' : '平板' }}
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryDeliveryDeviceCondition.pageNum"
          v-model:pageSize="queryDeliveryDeviceCondition.pageSize"
          :defaultPageSize="queryDeliveryDeviceCondition.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="queryDevice"
          @showSizeChange="queryDevice"
      />
    </div>
  </a-modal>

</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import {regionData} from "element-china-area-data";
import {message, Modal} from "ant-design-vue";
import {deliveryOrderApi} from "/@/views/business/storage/delivery-order";
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {storageAreaApi} from "/@/views/business/storage/storage-area";
import {storageRackApi} from "/@/views/business/storage/storage-rack";


const serviceDeviceTableColumns = [
  {
    align: 'center',
    title: '机器编码',
    dataIndex: 'machineCode',
    width: 180,
  },
  {
    align: 'center',
    title: '序列号',
    dataIndex: 'serialNumber',
    width: 180,
  },
  {
    align: 'center',
    title: 'IMEI',
    dataIndex: 'imei',
    width: 180,
  },
  {
    align: 'center',
    title: '仓储区',
    dataIndex: 'storageName',
    width: 120,
  },
  {
    align: 'center',
    title: '货架',
    dataIndex: 'rackName',
    width: 120,
  },
  {
    align: 'center',
    title: '型号',
    dataIndex: 'modelName',
    width: 200,
  },
  {
    align: 'center',
    title: '所属品类',
    dataIndex: 'category',
    width: 120,
  },
];
const deviceTableColumns = [...serviceDeviceTableColumns,
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 120,
    fixed: 'right'
  }]
const deviceList = ref([]);
const serviceDeviceList = ref([]);

const expareaCode = ref([]);
const formData = reactive({
  deliveryType: 2,// 出库单类型 1回收退货 2第三方销售 3线下销售
  deliveryWay: 1,//出库单方式 1快递邮寄 2线下配送 ,
  expType: 1,//快递公司 1顺丰 2其他
  freightFlag: 0,//邮费承担 0我司承担 1用户承担
  lnker: undefined,//收件人
  lnktel: undefined,//手机号
  exparea: undefined,//收件地区
  expdtl: undefined,//详细地址
  machineIds: undefined,//出库机器id
})

const addDeviceModal = reactive({
  visible: false,
});
const storageAreaOptions = ref([]);
const storageRackOptions = ref([]);
const brandOptions = ref([]);
const total = ref();
let selectedRows = [];
const selectedRowKeys = ref([]);

function getCheckboxProps (record) {
  return  {
    disabled: deviceList.value.findIndex(item => item.id === record.id) !== -1,
  }
}

onMounted(()=>{
  brandApi.queryPage({
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    brandOptions.value = res.data.list;
  });
  storageAreaApi.queryPage({
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    storageAreaOptions.value = res.data.list;
  });
})

function areaChange(v, selectedOptions) {
  formData.exparea = selectedOptions.map(o => o.label).join('@');
}

function cancel() {
  window.history.back();
}

function save() {
  if (!formData.lnker || !formData.lnker.trim()) {
    return message.error('请输入收件人姓名')
  }
  if (!/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/.test(formData.lnktel)) {
    return message.error('请输入正确的手机号码')
  }
  if (!formData.exparea || !formData.exparea.trim()) {
    return message.error('请选择地区')
  }
  if (!formData.expdtl || !formData.expdtl.trim()) {
    return message.error('请输入详细地址')
  }
  if (!deviceList.value.length){
    return message.error('请选择要出库的设备')
  }
  deliveryOrderApi.addDelivery({
    ...formData,
    machineIds: deviceList.value.map(item=>item.id).join(',')
  }).then(res=>{
    message.success('添加成功')
    cancel();
  })
  console.log(formData)
}

function deleteDevice(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除该设备吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      deviceList.value = deviceList.value.filter(item=>item.id!==record.id);
      console.log(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

function storageAreaChange() {
  storageRackOptions.value = [];
  queryDeliveryDeviceCondition.storageRackId = undefined;
  if (!queryDeliveryDeviceCondition.storageId) {
    return;
  }
  storageRackApi.queryPage({
    storageId: queryDeliveryDeviceCondition.storageId,
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    storageRackOptions.value = res.data.list;
  });
}

const queryDeliveryDeviceConditionDefault = {
  keyword: undefined,
  storageId: undefined,
  storageRackId: undefined,
  modelName: undefined,
  brancId: undefined,
  category: undefined,
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryDeliveryDeviceCondition = reactive({...queryDeliveryDeviceConditionDefault})

function showAddDeviceModal() {
  addDeviceModal.visible = true;
  selectedRows = deviceList.value;
  selectedRowKeys.value = selectedRows.map(item=>item.id);
  queryDevice();
}

function hideAddDeviceModal() {
  addDeviceModal.visible = false;
  resetQuery();
}

function saveAddDevice() {
  if (!selectedRows.length){
    return message.warn('请选择要添加的设备')
  }
  selectedRows.filter(item=>{
    if (deviceList.value.some(d=>d.id===item.id)){
      return true;
    }
    return false;
  })
  deviceList.value.push(...selectedRows);
  hideAddDeviceModal();
}

function rowSelectionChange(keyArray, selected){
  console.log(`selectedRowKeys: ${keyArray}`, 'selectedRows: ', selected);
  selectedRowKeys.value = keyArray;
  selectedRows = selected;
}
function resetPageNumAjaxQuery(){
  queryDeliveryDeviceCondition.pageNum = 1;
  queryDevice();
}
function resetQuery(){
  Object.assign(queryDeliveryDeviceCondition,queryDeliveryDeviceConditionDefault);
}
function queryDevice() {
  selectedRowKeys.value = [];
  selectedRows = [];
  deliveryOrderApi.queryDeliveryDevice(queryDeliveryDeviceCondition).then(res => {
    serviceDeviceList.value = res.data.list;
    total.value = res.data.total;
    console.log(res)
  });
}
</script>

<style lang="less" scoped>
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 16px;
}

.label {
  display: inline-block;
  width: 120px;
  text-align: right;
  margin-right: 8px;
}

.required:before {
  color: red;
  content: '*';
}
</style>